package com.jin.model;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.core.type.TypeReference;
import com.jin.util.GenericAndJson;
import com.jin.util.ListAndJson;
import com.jin.util.MapAndJson;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.Where;

import javax.persistence.*;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Entity
@Getter
@Setter
//SKU不需要配置导航属性，因为业务里面没有通过sku查看spu的业务
@Where(clause = "delete_time is null and online = 1")
public class Sku {
    @Id
    private Long id;
    private BigDecimal price;
    private BigDecimal discountPrice;
    private Boolean online;
    private String img;
    private String title;
    private Long spuId;
    private Long categoryId;
    private Long rootCategoryId;
    //规格（几个实体一同构建）最精妙的设计就是把多组的sku放在数据库中，现在来把这多组的sku用对象的方式,多组映射成List<Object>

    private String specs;
    //sku的唯一标识
    private String code;
    //库存量
    private Long stock;

    public BigDecimal getActualPrice(){
        return discountPrice == null ? this.price :this.discountPrice;
    }


    //测试代码 调用的是反序列化：把数据库中的json格式的字段（其实还是字符串类型）的数据转换成对象（json对象）,单组映射成map
//    @Convert(converter = MapAndJson.class)
//    private Map<String,Object> test;


    //get的过程实际上就是反序列化的过程
    public List<Spec> getSpecs() {
       if (specs==null){
           //返回一个空list
           return Collections.emptyList();
       }
       //匿名内部类
       return GenericAndJson.jsonToList(specs, new TypeReference<List<Spec>>() {
       });
//        return GenericAndJson.jsonToList(specs);
    }

    //set的过程就是序列化的过程
    public void setSpecs(List<Spec> specs) {
        if (specs.isEmpty()){
            return;
        }
        this.specs = GenericAndJson.objectToJson(specs);
    }

    @JsonIgnore
    public List<String> getSpecValueList() {
        return this.getSpecs().stream().map(Spec::getValue).collect(Collectors.toList());
    }
}
